const { parse, tokenizers } = require('comment-parser');
class Parser {
  /**
   * 解析注释文档
   * @param {string} jscontent 
   */
  constructor(jscontent) {
    this.content = jscontent || '';
    this.comments = undefined;
    this.documents = [];
    this.parse();
  }
  parse() {
    if (this.content === '') {
      return;
    }
    try {
      const comments = parse(this.content, {
        tokenizers: [
          spec => {
            const {
              tokens
            } = spec.source[0];
            const match = tokens.description.match(/\s*(@(\S+))\((\s*)/);

            if (match === null) {
              spec.problems.push({
                code: 'spec:tag:prefix',
                message: 'tag should start with "@" symbol',
                line: spec.source[0].number,
                critical: true
              });
              return spec;
            }

            tokens.tag = match[1];
            tokens.postTag = match[3];
            tokens.description = tokens.description.slice(match[0].length);
            spec.tag = match[2];
            return spec;
          },
          (spec) => {
            spec = tokenizers.description()(spec);
            if (spec && spec.description) {
              spec.description = spec.description.replace(/\)$/, '');
            }
            return spec;
          }
        ]
      });
      this.comments = comments;
    } catch (e) {
      throw new Error('语法树解析失败:' + e );
    }
  }  
}

module.exports = Parser;